<template>
<!-- 产品/物料明细 -->
  <p-card :bordered="false" :class="'cust-erp-sub-tab'">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <p-form layout="inline" @keyup.enter.native="searchQuery">
        <p-row :gutter="24"></p-row>
      </p-form>
    </div>
    <!-- 查询区域-END -->

    <p-modal v-model="modalVisible" :title="modalTitle" okText="确定" :width="900" cancelText="取消" @ok="sureAddProduction" >
      <p-row :gutter="24">
        <p-col :span="2" >
          <p-form-item label="产品编码"></p-form-item>
        </p-col>
        <p-col :span="20" @click="clickMcodeInput">
            <p-input placeholder="请选择产品编码" v-model="pr.mcode" readOnly ></p-input>
        </p-col>


      </p-row>

      <p-row :gutter="24">
        <p-col :span="2">
          <p-form-item label="产品名称">

          </p-form-item>
        </p-col>
        <p-col :span="20">
          <p-input  v-model="pr.mname" disabled></p-input>
        </p-col>

      </p-row>


    </p-modal>


    <p-modal v-model="productionListVisible"  title="选择产品" :width="900" okText="确定" cancelText="取消" @ok="selectProductionFinish">
       <p-row>
         <p-form  :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
           <p-form-item label="产品编码">
             <p-input
                    v-model="selectMcode" @change="beforeProductionQuery"
             />
           </p-form-item>

         </p-form>
       </p-row>
      <p-row>
        <p-table
                ref="table"
                size="middle"
                bordered
                rowKey="id"
                :columns="productionColumns"
                :scroll="tableScroll"
                :dataSource="productionList"
                :loading="loading"
                :pagination="false"

                :rowSelection="{selectedRowKeys: productionKeys,onChange: productionSelectChange,type:'radio'}"

        >


        </p-table>
        <p-pagination
                v-model="productionIpagination.current"
                :total="productionIpagination.total"
                :page-size="productionIpagination.size"
                :showQuickJumper="true"
                @change="productionQuery"
                @showSizeChange="productionQuery"
                :show-total="total => `总共 ${productionIpagination.total} 条`"
        />
      </p-row>

    </p-modal>


    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <p-button v-if="mainId" @click="openAddBtn" type="primary" icon="plus">新增</p-button>

      <template v-if="cgButtonList && cgButtonList.length>0" v-for="(item,index) in cgButtonList">
        <p-button
          v-if=" item.optType=='js' "
          :key=" 'cgbtn'+index "
          @click="cgButtonJsHandler(item.buttonCode)"
          type="primary"
          :icon="item.buttonIcon"
        >{{ item.buttonName }}</p-button>
        <p-button
          v-else-if=" item.optType=='action' "
          :key=" 'cgbtn'+index "
          @click="cgButtonActionHandler(item.buttonCode)"
          type="primary"
          :icon="item.buttonIcon"
        >{{ item.buttonName }}</p-button>
      </template>

      <p-dropdown v-if="selectedRowKeys.length > 0">
        <p-menu slot="overlay">
          <p-menu-item key="1" @click="batchDel">
            <p-icon type="delete" />删除
          </p-menu-item>
        </p-menu>
        <p-button style="margin-left: 8px">
          批量操作
          <p-icon type="down" />
        </p-button>
      </p-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <p-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :scroll="tableScroll"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        :customRow="clickThenSelect"
        :rowClassName="setRowClassName"
        @change="handleTableChange"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无此图片</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt="图片不存在"
            style="max-width:80px;font-size: 12px;font-style: italic;"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无此文件</span>
          <p-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="uploadFile(text)"
          >下载</p-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="openAddBtn2(record)">编辑</a>

          <p-divider type="vertical" />
          <p-dropdown>
            <a class="ant-dropdown-link">
              更多
              <p-icon type="down" />
            </a>
            <p-menu slot="overlay">
              <p-menu-item>
                <p-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </p-popconfirm>
              </p-menu-item>
              <template
                v-if="cgButtonLinkList && cgButtonLinkList.length>0"
                v-for="(btnItem,btnIndex) in cgButtonLinkList"
              >
                <p-menu-item :key=" 'cgbtnLink'+btnIndex " v-if="showLinkButton(btnItem,record)">
                  <a
                    href="javascript:void(0);"
                    @click="cgButtonLinkHandler(record,btnItem.buttonCode,btnItem.optType)"
                  >
                    <p-icon v-if="btnItem.buttonIcon" :type="btnItem.buttonIcon" />
                    {{ btnItem.buttonName }}
                  </a>
                </p-menu-item>
              </template>
            </p-menu>
          </p-dropdown>
        </span>
      </p-table>
    </div>

    <!--<mesQcQualityFileProductDetail-modal
      ref="modalForm"
      :EnhanceJS="EnhanceJS"
      @ok="modalFormOk"
      :mainId="mainId"
    ></mesQcQualityFileProductDetail-modal>-->
  </p-card>
</template>

<script>
import { JeecgListMixin } from "@/mixins/JeecgListMixin";
import MesQcQualityFileProductDetailModal from "./modules/MesQcQualityFileProductDetailModal";
import ButtonExpHandler from "@/components/jeecgbiz/modules/ButtonExpHandler";
import { putAction,postAction, getAction, deleteAction } from "@/api/manage";

export default {
  name: "MesQcQualityFileProductDetailList",
  mixins: [JeecgListMixin],
  components: { MesQcQualityFileProductDetailModal },
  props: {
    mainId: {
      type: String,
      default: "",
      required: false,
    },
  },
  watch: {
    mainId: {
      immediate: true,
      handler(val) {
        if (!this.mainId) {
          this.clearList();
        } else {
          this.queryParam["mesQualityFileManagementId"] = val;
          this.loadData(1);
        }
      },
    },
  },

/*:columns="productionColumns"
:scroll="tableScroll"
:dataSource="productionList"
:pagination="productionIpagination"*/
  data() {
    return {
      description: "文件管理管理页面",
      disableMixinCreated: true,
      EnhanceJS: "",
      cgButtonLinkList: [],
      cgButtonList: [],
      code: "",
      selectMcode:'',
      productForm:this.$form.createForm(this, { name: 'coordinated' }),
      modalTitle:'',


      currentState:1,

      currentEdit:{},


      productionKeys:[],
      productionRows:[],
      productionColumns:[
        {
          title:'产品编号',
          align:'center',
          dataIndex:'mcode',
        },
        {
          title:'产品名称',
          align:'center',
          dataIndex:'mname',
        }
      ],
      rowId:0,
      productionList:[],
      newPageSize:0,
      productionIpagination:{
        current: 1,
        size: 10,
        pageSizeOptions: ["10", "20", "50"],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },

        total: 0,
      },

      pr:{
        id:0,
        mcode:'',
        mname:'',
      },
      modalVisible:false,
      productionListVisible:false,

      // 表头
      columns: [
        {
          title: "序号",
          dataIndex: "",
          key: "rowIndex",
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          },
        },

        {
          title: "产品编码",
          align: "center",
          dataIndex: "mcode",
        },
        {
          title: "产品名称",
          align: "center",
          dataIndex: "mname",
        },

        {
          title: "创建者",
          align: "center",
          dataIndex: "createBy",
        },
        {
          title: "创建日期",
          align: "center",
          dataIndex: "createTime",
        },
        {
          title: "修改者",
          align: "center",
          dataIndex: "updateBy",
        },
        {
          title: "修改日期",
          align: "center",
          dataIndex: "updateTime",
        },
        {
          title: "备注",
          align: "center",
          dataIndex: "remark",
        },
        {
          title: "编辑",
          dataIndex: "action",
          align: "center",
          scopedSlots: { customRender: "action" },
        },
      ],
      url: {
        list:
          "/mes-quality/mesQcQualityFileManagement/listMesQcQualityFileProductDetailByMainId",
        delete:
          "/mes-quality/mesQcQualityFileManagement/deleteMesQcQualityFileProductDetail",
        deleteBatch:
          "/mes-quality/mesQcQualityFileManagement/deleteBatchMesQcQualityFileProductDetail",
        getColumns: "/mes-quality/online/cgform/api/getColumns/",
        buttonAction: "/mes-quality/online/cgform/api/doButton",
      },
      dictOptions: {
        fileType: [],
        status: [],
      },
    };
  },

  computed: {
    tableScroll: function () {
      if (this.columns.length > 12) {
        return { x: this.columns.length * 160 + 40 };
      }
    },
  },

  created() {
    this.setdefColumns();
    this.initButtonList();
  },
  methods: {
    selectProductionFinish(){
      console.log(this.productionRows[0])
      if(this.productionRows.length>0){
        let obj = this.productionRows[0];
        this.pr.mid  = obj.id;
        this.pr.mcode  = obj.mcode;
        this.pr.mname  = obj.mname;
      }
      this.productionListVisible = false;
    },

    onSelectChange(selectedRowKeys, selectionRows) {
      this.rowId = 0,
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    clickThenSelect(record) {
      return {
        on: {
          click: () => {
            if(record.id){
              console.log(record.id)
              this.rowId = record.id;
              this.selectedRowKeys = [];
              this.selectionRows = [];
              //this.onSelectChange(record.id.split(","), [record]);
            }

          },
        },
      };
    },

    setRowClassName(record){
      return record.id === this.rowId ? 'clickRowStyl' : '';
    },
    sureAddProduction(){
      let flag = true;
      if(this.pr.mid = 0||!this.pr.mid||this.pr.mid===''){
        flag  = false;
        this.$message.error("请选择产品");
      }


      if(flag){
        switch (this.currentState) {
          case 1:
            this.productionAdd();
            break;

          case 2:
            this.productionEdit();
            break;
        }
      }

    },


    productionCancel(){
      this.loadData();
    },


    productionEdit(){
      let data = this.currentEdit;

      data.mid = this.pr.mid;
      data.mcode = this.pr.mcode;
      data.mname = this.pr.mname;
      putAction('/mes-quality/mesQcQualityFileManagement/editMesQcQualityFileProductDetail',data).then(res=>{
        if(res.success){
          this.modalVisible= false;
          this.$message.success("新增成功！");
          this.loadData();
        }else{
          this.$message.warning(res.msg);
        }
      })
    },

    productionAdd(){
      let data = {
        mesQualityFileManagementId:this.mainId,
        mid:parseInt(this.pr.id),
        mcode:this.pr.mcode,
        mname:this.pr.mname,
      }

      postAction('/mes-quality/mesQcQualityFileManagement/addMesQcQualityFileProductDetail',data).then(res=>{
        if(res.success){
          this.modalVisible= false;
          this.$message.success("新增成功！");
          this.loadData();
        }else{
          this.$message.warning(res.msg);
        }
      })
    },


    productionSelectChange(selectedRowKeys, selectionRows){
      this.productionKeys = selectedRowKeys;
      this.productionRows = selectionRows;
    },
    setdefColumns() {
      if (this.columns.length > 12) {
        let arrLength = this.columns.length - 1;
        this.columns[arrLength]["fixed"] = "right";
        this.columns[arrLength]["width"] = 200;
        this.columns[0]["width"] = 70;
        this.columns[0]["fixed"] = "left";
      }
    },

    openAddBtn(){
      this.pr={id:0,mcode:'',mname:''};
      this.modalVisible = true;
      this.modalTitle = '产品/物料明细新增';
      this.currentState = 1;
    },
    openAddBtn2(record){
      this.currentEdit = record;
      this.pr={id:record.mid,mcode:record.mcode,mname:record.mname};

      this.currentState = 2;
      this.modalVisible = true;
      this.modalTitle = '产品/物料明细编辑';
    },


    clickMcodeInput(){
      this.productionListVisible = true;
      this.selectMcode='';
      this.newPageSize = 1;
      this.productionQuery();

    },

    beforeProductionQuery(){
      this.newPageSize = 1;
      this.productionQuery();
    },

    productionQuery(){
      let param = {
        pageNo:this.productionIpagination.current,
        pageSize:this.productionIpagination.size,
      }
      param.mcode = this.selectMcode;

      if(this.newPageSize=1){
        param.pageSize = 1;
      }else{
        this.newPageSize = param.pageSize;
      }
      console.log(param)

      getAction('/basic-business/auto/baCpinfoMain/queryProductList',param).then(res=>{
        if(res.success){
          this.productionIpagination = res.data;
          this.productionList = res.data.records;
        }else{
          this.$message.error("获取物料数据报错");
        }
      })
    },


    clearList() {
      this.dataSource = [];
      this.selectedRowKeys = [];
      this.ipagination.current = 1;
    },
    //2020/7/9
    initDictConfig() {},
    showLinkButton(item, record) {
      let btn = new ButtonExpHandler(item.exp, record);
      return btn.show;
    },
    initButtonList() {
      getAction(`${this.url.getColumns}6f1c629f0073427c987649a6776eaca4`).then(
        (res) => {
          console.log("--获取自定义按钮->>", res);
          if (res.success) {
            this.code = res.data.code;
            this.initCgButtonList(res.data.cgButtonList);
            this.initCgEnhanceJs(res.data.enhanceJs);
          } else {
            this.$message.warning(res.msg);
          }
        }
      );
    },
    initCgEnhanceJs(enhanceJs) {
      //console.log("--onlineList-js增强",enhanceJs)
      if (enhanceJs) {
        let Obj = eval("(" + enhanceJs + ")");
        this.EnhanceJS = new Obj(getAction, postAction, deleteAction);
        this.cgButtonJsHandler("created");
      } else {
        this.EnhanceJS = "";
      }
    },
    initCgButtonList(btnList) {
      let linkArr = [];
      let buttonArr = [];
      if (btnList && btnList.length > 0) {
        for (let i = 0; i < btnList.length; i++) {
          let temp = btnList[i];
          if (temp.buttonStyle == "button") {
            buttonArr.push(temp);
          } else if (temp.buttonStyle == "link") {
            linkArr.push(temp);
          }
        }
      }
      this.cgButtonLinkList = [...linkArr];
      this.cgButtonList = [...buttonArr];
      console.log("链接增强", this.cgButtonLinkList);
    },
    cgButtonJsHandler(buttonCode) {
      if (this.EnhanceJS[buttonCode]) {
        this.EnhanceJS[buttonCode](this);
      }
    },
    cgButtonActionHandler(buttonCode) {
      //处理自定义button的 需要配置该button自定义sql
      if (!this.selectedRowKeys || this.selectedRowKeys.length == 0) {
        this.$message.warning("请先选中一条记录");
        return false;
      }
      if (this.selectedRowKeys.length > 1) {
        this.$message.warning("请只选中一条记录");
        return false;
      }
      let params = {
        formId: this.code,
        buttonCode: buttonCode,
        dataId: this.selectedRowKeys[0],
      };
      console.log("自定义按钮请求后台参数：", params);
      postAction(this.url.buttonAction, params).then((res) => {
        if (res.success) {
          this.loadData();
          this.$message.success("处理完成!");
        } else {
          this.$message.warning("处理失败!");
        }
      });
    },
    cgButtonLinkHandler(record, buttonCode, optType) {
      if (optType == "js") {
        if (this.EnhanceJS[buttonCode]) {
          this.EnhanceJS[buttonCode](this, record);
        }
      } else if (optType == "action") {
        let params = {
          formId: this.code,
          buttonCode: buttonCode,
          dataId: record.id,
        };
        console.log("自定义按钮link请求后台参数：", params);
        postAction(this.url.buttonAction, params).then((res) => {
          if (res.success) {
            this.loadData();
            this.$message.success("处理完成!");
          } else {
            this.$message.warning("处理失败!");
          }
        });
      }
    },
  },
};
</script>
<style scoped>
@import "~@assets/less/common.less";
/deep/.clickRowStyl td{
  background:#00b4ed !important;
}
/deep/.ant-table-tbody>.clickRowStyl:hover>td {
  background-color:#00b4ed
}
</style>
